﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NCP.Infrastructure.Common.Domain;
using NCP.Recruiting.ApplicationServices.Interfaces;
using NCP.Recruiting.ApplicationServices.Messaging.Companies;
using NCP.Recruiting.ApplicationServices.ViewModels;
using NCP.Recruiting.WebApp.Extensions;
using NCP.Recruiting.WebApp.Models;
using NCP.Recruiting.WebApp.Models.Company;
using NCP.Recruiting.Web.Framework.Controllers;
using NCP.Recruiting.ApplicationServices.Messaging.Photos;

namespace NCP.Recruiting.WebApp.Controllers
{
    public class CompanyController : AuthorizedController
    {
        private readonly ICompanyAppService _companyAppService;
        private readonly IPhotoAppService _photoAppService;

        public CompanyController(ICompanyAppService companyAppService, IPhotoAppService photoAppService)
            : base(companyAppService)
        {
            _companyAppService = companyAppService;
            _photoAppService = photoAppService;
        }

        public ActionResult List()
        {
            GetCompaniesResponse response = _companyAppService.GetAll();

            return View(response.Companies);
        }

        public ActionResult Register()
        {
            return View();
        }

        [Authorize]
        public ActionResult Edit()
        {
            GetCompanyResponse response = _companyAppService.GetCompanyById(new GetCompanyRequest() { Id = this.CurrentUserId });

            return View(ConstructForm(response.Company));
        }

        [Authorize]
        public ActionResult ChangePassword()
        {
            var formModel = new ChangePasswordFormModel { Id = this.CurrentUserId };
            return View(formModel);
        }

        [HttpPost]
        public ActionResult Edit(CompanyFormModel model, HttpPostedFileBase logofile)
        {
            if (logofile != null)
            {
                byte[] logodata = new byte[logofile.ContentLength];

                logofile.InputStream.Read(logodata, 0, logofile.ContentLength);

                model.Logo = logodata;

                _companyAppService.UpdateCompany(new UpdateCompanyRequest { CompanyForm = model });

                return Content("SaveLogo");
            }


            if (ModelState.IsValid)
            {
                _companyAppService.UpdateCompany(new UpdateCompanyRequest { CompanyForm = model });
            }

            return Content("SaveInfo");
        }


        private CompanyFormModel ConstructForm(CompanyViewModel model)
        {
            var frommodel = new CompanyFormModel
            {
                Id = model.Id,
                CompanyName = model.CompanyName,
                ShortName = model.ShortName,
                Shortcut = model.Shortcut,
                Industry = model.Industry,
                CompanyType = model.CompanyType,
                Employees = model.Employees,
                BusinessLicense = model.BusinessLicense,
                RegisteredCapital = model.RegisteredCapital,
                EstablishedOn = model.EstablishedOn,
                Overview = model.Overview,
                Business = model.Business,
                Province = model.Province,
                City = model.City,
                Address = model.Address,
                PostalCode = model.PostalCode,
                Contact = model.Contact,
                Tel = model.Tel,
                Fax = model.Fax,
                Mobile = model.Mobile,
                Email = model.Email,
                WebSite = model.WebSite,
                Park = model.Park,
                EnableShortName = model.EnableShortName,
                TemplateId = model.TemplateId
            };

            frommodel.Photos = _photoAppService.GetPhotos(new GetPhotosRequest(frommodel.Id)).Photos;


            return SetDropDownList(frommodel);
        }

        private CompanyFormModel SetDropDownList(CompanyFormModel model)
        {
            //行业类别
            model.AvailableIndustres = Common.GenerateDropDownListSource(LovType.Industry);
            //公司性质
            model.AvailableCompanyTypes = Common.GenerateDropDownListSource(LovType.CompanyType);

            model.ProvinceList = Common.GenerateDropDownListSource(LovType.Regionalism);

            if (model.Province != null)
            {
                model.CityList = Common.GenerateDropDownSubListSource(model.Province);
            }

            return model;
        }

        //返回城市列表
        public ActionResult GetCities(int? id)
        {
            var cityList = LovHandler.GetListByParentId(LovHandler.ConvertLovValueToGuid(id.Value));
            if (Request.IsAjaxRequest())
            {
                return Json(cityList, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return View("");
            }
        }


        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="filewall">文件</param>
        /// <param name="filewalltitle">名称</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult FileUpload(HttpPostedFileBase filewall, string filewalltitle, string Id)
        {

            byte[] imagedata = new byte[filewall.ContentLength];

            filewall.InputStream.Read(imagedata, 0, filewall.ContentLength);
            PhotoFromModel model = new PhotoFromModel()
            {
                CompanyId = Guid.Parse(Id),
                MimeType = filewall.ContentType,
                Title = filewalltitle,
                Size = filewall.ContentLength,
                PhotoBinary = imagedata
            };

            var photoRequest = new CreatePhotoRequest() {PhotoProperties=model };
            var response = _photoAppService.CreatePhoto(photoRequest);

            if (response.Errors.Count()==0)
            {


                return Json(_photoAppService.GetPhotos(new GetPhotosRequest(Guid.Parse(Id))).Photos.Select(x => new PhotoFromModel() { Id=x.Id,Title=x.Title }));

            }
            else
            {
                return Content("上传失败");
            }


        }

        public FileContentResult GetImage(string fileid)
        {
            var response = _photoAppService.GetPhoto(new GetPhotoRequest(Guid.Parse(fileid)));
            return File(response.ViewModel.PhotoBinary, response.ViewModel.MimeType);

        }

        public FileContentResult GetLogoImage()
        {
            GetCompanyResponse response = _companyAppService.GetCompanyById(new GetCompanyRequest() { Id = this.CurrentUserId });
            if (response.Company.Logo != null)
            {
                return File(response.Company.Logo, "image/jpeg");
            }
            else
            {
                return null;
            }

        }

        public ActionResult DeleteImg(string id)
        {
            DeletePhotoResponse response = _photoAppService.DeletePhoto(new DeletePhotoRequest(Guid.Parse(id)));

            return Json(id);
        }

        public ActionResult DeleteLogo()
        {
            CompanyFormModel model= new CompanyFormModel(){ Id=this.CurrentUserId};
            UpdateCompanyResponse response = _companyAppService.UpdateCompanyLogo(new UpdateCompanyRequest() { CompanyForm = model });

            return Content("");
        }




    }
}
